// mayaoqing haixiazai

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import "package:get/get.dart";
import 'package:osg/controllers/http.dart';


import 'package:flutter/foundation.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:dio/dio.dart';
import 'package:osg/controllers/my_method.dart';


class Invitation extends StatefulWidget {
  
  const Invitation({super.key});

  @override
  State<Invitation> createState() => _SettingPageState();
}



class _SettingPageState extends State<Invitation> {


   Future<void> copyToClipboard(BuildContext context,textToCopy) async {
    await Clipboard.setData(ClipboardData(text: textToCopy));

    Get.find<HTTPS>().showTost('已复制到剪贴板');

  }

  

RxMap info={}.obs;
RxList list=[].obs;

_saveNetworkImage() async {
    var response = await Dio().get("${info['qr']}", options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaverPlus.saveImage(Uint8List.fromList(response.data), quality: 60, name: "hello");
    if(result['isSuccess']==true){
      Get.find<HTTPS>().showTost('保存成功');
    }else{
      Get.find<HTTPS>().showTost('保存失败');
    }
    Timer.periodic(const Duration(seconds: 1), (timer) {

      timer.cancel();
      Get.back();
    });

  }

//    Future<void> saveImage(String imageUrl) async {
//   try {
//     // 获取图片数据
//     final response = await http.get(Uri.parse(imageUrl));
//     final bytes = response.bodyBytes;
//     final blob = html.Blob([Uint8List.fromList(bytes)]);
//     final url = html.Url.createObjectUrlFromBlob(blob);

//     // 创建隐藏的<a>标签并触发下载
//     final anchor = html.AnchorElement(href: url)
//       ..setAttribute('download', 'image.png')
//       ..style.display = 'none';
//     html.document.body?.children.add(anchor);
//     anchor.click();

//     // 清理
//     html.document.body?.children.remove(anchor);
//     html.Url.revokeObjectUrl(url);
//     Get.find<HTTPS>().showTost('保存成功');
//   } catch (e) {
//     print('保存图片失败: $e');
//   }
// }

getInfo(){
  
 Get.find<HTTPS>().getData('/user/invite', {}).then((res){
      if(res!=null){
        info.value = res;
        list.value = res['list'];
      }
    });

}

  @override
  void initState() {
    super.initState();


     WidgetsBinding.instance.addPostFrameCallback((_) {
      getInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0XFF040E24),
        body: ListView(
      children: [
        Stack(
          children: [
            Container(
              margin: EdgeInsets.only(top: 45),
              child: Image.asset(
                'static/images/inctonhimg.png',
                fit: BoxFit.fitWidth,
              ),
            ),
            Positioned(
              left: 8.0,
              top:0,
              child: IconButton(
                onPressed: () {
                  Get.back();
                  print('object');
                },
                icon: Image.asset(
                  'static/images/bback.png',
                  width: 22,
                  fit: BoxFit.fitWidth,
                ),
              ),
            ),
            Positioned(
              left: 70,
              right:70,
              bottom: 25,
              child: 
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  GestureDetector(
                    onTap: (){
                      final weburl = Get.find<MyMethod>().myget('weburl');
                      copyToClipboard(context,'$weburl/#/login/register_tow?invite_code=${info['my_invite']}');
                    },
                    child:Column(
                    children: [
                      Image.asset('static/web/mayaoqing.png',width: 40,fit: BoxFit.fitWidth,),
                      SizedBox(height: 5,),
                      Text('复制邀请链接',style: TextStyle(fontSize: 12,color: Color(0XFF333333))),
                    ],
                  ) ,
                  )
                  ,
                GestureDetector(
                  onTap: (){
                    Get.dialog(
                AlertDialog(
                  backgroundColor: Colors.transparent,
                  content: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.network(
                        '${info['qr']}',
                        width: 250,
                        fit: BoxFit.fitWidth,
                      ),
                      GestureDetector(
                        onTap: (){
                          if (kIsWeb) {
                              // saveImage('$qr');
                            } else {
                              _saveNetworkImage();
                            }
                        },
                        child:  Container(
                        margin: EdgeInsets.only(top: 20),
                          height:40,
                          width: 130,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Color(0XFF333333),
                          borderRadius: BorderRadius.circular(15)
                        ),
                        child:Text('保存图片',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
                      ),
                      )
                     
                    ],
                  ),
                ),
              );
                  },
                  child: Column(
                    children: [
                      Image.asset('static/web/haixiazai.png',width: 40,fit: BoxFit.fitWidth,),
                      SizedBox(height: 5,),
                      Text('下载邀请海报',style: TextStyle(fontSize: 12,color: Color(0XFF333333))),
                    ],
                  ),
                ),
              ],)

            ),
          ],
        ),
        Container(
          color: Color(0XFF0f172b),
          alignment: Alignment.center,
          height: 50,
          child: Text(
            '保存海报或复制邀请码分享好友获得奖励',
            style: TextStyle(fontSize: 14, color: Color(0xffFFFFFF)),
          ),
        ),
     


        // Align(
        //   alignment: Alignment.center,
        //   child: Container(
        //     width: 150,
        //     height: 40,
        //     margin: EdgeInsets.only(top: 30, bottom: 30),
        //     decoration: BoxDecoration(
        //         color: Color(0xff333333),
        //         borderRadius: BorderRadius.circular(50)),
        //     child: TextButton(
        //       style: ButtonStyle(
        //         textStyle: WidgetStateProperty.all(TextStyle(fontSize: 16)),
        //         backgroundColor: WidgetStateProperty.all(Color(0xff333333)),
        //       ),
        //       onPressed: () {
        //         Get.toNamed('/poster?qr=${info['qr']}');
        //         // 触发点击逻辑 :ml-citation{ref="1,3" data="citationList"}
        //       },
        //       child: Text(
        //         '立即邀请',
        //         style: TextStyle(color: Color(0xffffffff)),
        //       ),
        //     ),
        //   ), // 左侧对齐且宽度生效
        // ),
      
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 15),
              Row(
                children: [
                  Text(
                    '我的邀请',
                    style: TextStyle(fontSize: 20,color: Color(0XFFFFFFFF)),
                  ),
                ],
              ),
              Row(
                children: [
                  Text(
                    '已邀请',
                    style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                  ),
                  Obx(()=>
                    Text(
                      '${info['invite_num']}',
                      style: TextStyle(fontSize: 12,color: Color(0XFFFFFFFF))
                    )
                  ),
                    Text(
                    '人，有效邀请',
                    style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                  ),
                     Obx(()=>
                    Text(
                      '${info['invite_idcard']}',
                      style: TextStyle(fontSize: 12,color: Color(0XFFFFFFFF))
                    )
                  ),
                    Text(
                    '人，无效邀请',
                    style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                  ),
                  Obx(()=>
                    info.isNotEmpty?
                    Text(
                      '${info['invite_num'] - info['invite_idcard']}',
                      style: TextStyle(fontSize: 12,color: Color(0XFFFFFFFF))
                    ):SizedBox()
                  ),
                 Text(
                    '人。',
                    style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                  ),
                ],
              ),

              SizedBox(height: 20), // 添加间距
              Obx(()=>
              Column(
                children: [
              for(var item in list.asMap().entries)
              Container(
                margin: EdgeInsets.only(bottom: 20),
                child:  Row(
                children: [
                  CircleAvatar(
                    radius: 22,
                    backgroundImage: NetworkImage('${item.value['headimg']}'),
                  ),
                  SizedBox(width: 10), // 添加间距
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${item.value['phone']}',
                          style: TextStyle(
                              fontSize: 15, fontWeight: FontWeight.bold,color: Color(0XFFFFFFFF)),
                        ),
                        SizedBox(height: 2), // 添加间距
                        Text(
                          '${item.value['created_at']}',
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 10), // 添加间距
                  Text(
                    '${item.value['idcard']}',
                    style: TextStyle(
                      color: Color(0xff999999),
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
              )
                ],
              )
                 
             
              )
             
             
              // SizedBox(height: 20), // 添加间距
              // Row(
              //   children: [
              //     CircleAvatar(
              //       radius: 22,
              //       backgroundImage:
              //           AssetImage('static/aaa.png'), // 替换为你的静态图片路径
              //     ),
              //     SizedBox(width: 10), // 添加间距
              //     Expanded(
              //       child: Column(
              //         crossAxisAlignment: CrossAxisAlignment.start,
              //         children: [
              //           Text(
              //             '啊呜严选啊呜严选',
              //             style: TextStyle(
              //                 fontSize: 15, fontWeight: FontWeight.bold),
              //           ),
              //           SizedBox(height: 2), // 添加间距
              //           Text(
              //             '2020.04.08 12:22',
              //             style: TextStyle(
              //               color: Colors.grey,
              //               fontSize: 12,
              //             ),
              //           ),
              //         ],
              //       ),
              //     ),
              //     SizedBox(width: 10), // 添加间距
              //     Text(
              //       '等待实名认证',
              //       style: TextStyle(
              //         color: Color(0xff999999),
              //         fontSize: 12,
              //       ),
              //     ),
              //   ],
              // ),
            
            ],
          ),
        )
      ],
    ));
  }
}
